package com.hudongwx.godoffood.fragment;

import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.LoginActivity;
import com.hudongwx.godoffood.activity.Shopping_Activity.ConfirmActivity;
import com.hudongwx.godoffood.activity.home_activity.FoodClassificationActivity;
import com.hudongwx.godoffood.activity.home_activity.FoodGoodsPageActivity;
import com.hudongwx.godoffood.activity.myActivity.CommunityMsgActivity;
import com.hudongwx.godoffood.activity.myActivity.MyCommunityActivity;
import com.hudongwx.godoffood.utils.DBUtils.DbOpenUtils;
import com.hudongwx.godoffood.utils.DBUtils.ShoppingCar;
import com.hudongwx.godoffood.utils.MyApplication;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.db.Selector;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hudongwx on 16-11-10.
 */
@ContentView(R.layout.fragment_shopping)
public class ShoppingFragment extends Fragment implements View.OnClickListener {
    CheckBox checkAll;
    FrameLayout frameLayout;
    LinearLayout linearLayout;
    TextView textViewl, carMoney;
    ListView MlistView;
    MyAdapter adapter;
    Button buy, gobuy;
    private int totalPrice = 0;
    int Mysum = 0;
    int MyseSum;
    private String TAG = "ShoppingFragment";
    private SparseArray<Boolean> mSelectState = new SparseArray<Boolean>();
    View view;
    List<ShoppingCar> all;
    RelativeLayout relativeLayout;
    DbManager db;

    /**
     * 判断是否登陆
     */
//    @Override
//    public void onResume() {
//        super.onResume();
//
//    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (view == null) {
            view = x.view().inject(this, inflater, container);
            inview(view);
            jsonDate();
        }

        return view;
    }

    /**
     * 社区的点击
     *
     * @param v
     */
    @Event(R.id.shopping_img)
    private void img(View v) {
        Intent intent = new Intent(getContext(), CommunityMsgActivity.class);
        startActivity(intent);

    }

    /**
     * 加载控件
     *
     * @param view
     */
    private void inview(View view) {
        textViewl = (TextView) view.findViewById(R.id.shopping_bianji);
        checkAll = (CheckBox) view.findViewById(R.id.shopping_checkBox_1);
        frameLayout = (FrameLayout) view.findViewById(R.id.shopping_frameLayout_1);
        linearLayout = (LinearLayout) view.findViewById(R.id.shopping_ll);
        MlistView = (ListView) view.findViewById(R.id.shopping_recyclerView);
        carMoney = (TextView) view.findViewById(R.id.shopping_tv_2);
        buy = (Button) view.findViewById(R.id.shopping_buy);
        gobuy = (Button) view.findViewById(R.id.shopping_null_button);
        relativeLayout = (RelativeLayout) view.findViewById(R.id.recycle_shopping_relativeLayout_1);
        checkAll.setOnClickListener(this);
        buy.setOnClickListener(this);
        textViewl.setOnClickListener(this);

    }

    /**
     * 在数据库中提取数据
     */
    private void jsonDate() {
        db = DbOpenUtils.getShoppingDb();
        try {
            all = db.findAll(ShoppingCar.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (MyApplication.getStorage("Uid").equals("1")) {
            if (all == null) {
                Log.i(TAG, "jsonDate: ");
                MlistView.setVisibility(View.GONE);
                relativeLayout.setVisibility(View.VISIBLE);
                //没有商品的时候按钮跳转商城
                gobuy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getContext(), FoodClassificationActivity.class);
                        startActivity(intent);
                    }
                });
                //有商品加载数据
            }else {
                relativeLayout.setVisibility(View.GONE);
                MlistView.setVisibility(View.VISIBLE);
                refreshListView();
            }
        }else {

            Log.i(TAG, "jsonDate: "+all);
        if (all == null) {
            Log.i(TAG, "jsonDate: ");
            MlistView.setVisibility(View.GONE);
            relativeLayout.setVisibility(View.VISIBLE);
            //没有商品的时候按钮跳转商城
            gobuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), FoodClassificationActivity.class);
                    startActivity(intent);
                }
            });
            //有商品加载数据
        }else {
            relativeLayout.setVisibility(View.GONE);
            MlistView.setVisibility(View.VISIBLE);
            refreshListView();
        }
    }}

    /**
     * 点击按钮的方法
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //编辑按钮
            case R.id.shopping_bianji:
                if (textViewl.getText().equals("编辑")) {
                    textViewl.setText("删除");
                    buy.setText("删除");
                    linearLayout.setVisibility(View.GONE);
                } else {
                    linearLayout.setVisibility(View.VISIBLE);
                    textViewl.setText("编辑");
                    buy.setText("去下单");
                }
                break;
            //全选
            case R.id.shopping_checkBox_1:
                if (checkAll.isChecked()) {

                    totalPrice = 0;
                    if (all != null) {
                        mSelectState.clear();
                        int size = all.size();
                        if (size == 0) {
                            return;
                        }
                        for (int i = 0; i < size; i++) {
                            int _id = (int) all.get(i).getId();
                            mSelectState.put(_id, true);
                            totalPrice += all.get(i).getNum() * all.get(i).getPrice();
                        }
                        refreshListView();
                        carMoney.setText("￥" + totalPrice + "");


                    }
                } else {
                    if (adapter != null) {
                        totalPrice = 0;
                        mSelectState.clear();
                        refreshListView();
                        carMoney.setText("￥" + 0.00 + "");
                    }
                }
                break;
            //购买的点击
            case R.id.shopping_buy:
                List<ShoppingCar> date = new ArrayList<>();
                if (buy.getText().equals("去下单")) {
                    if (MyApplication.getStorage("Uid").equals("1")) {
                        Log.i(TAG, "onClick: 在这");
                        Intent intent = new Intent(getContext(), ConfirmActivity.class);
                        mSelectState.size();
                        Mysum = 0;
                        for (int i = 0; i < mSelectState.size(); i++) {
                            int keyAt = mSelectState.keyAt(i);
                            Boolean aBoolean = mSelectState.get(keyAt);
                            if (aBoolean && mSelectState.size() != 0) {
                                Mysum += all.get(i).getNum();
                                ShoppingCar car = all.get(i);
                                date.add(new ShoppingCar(car.getName(), car.getPrice(), car.getType(), car.getNum(), car.getImg()));
                            }

                        }
                        intent.putExtra("date", date.toArray());
                        intent.putExtra("Mysum", Mysum + "");
                        intent.putExtra("money", carMoney.getText() + "");
                        startActivity(intent);

                    }else {
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    Log.i(TAG, "onClick:dsada ");
                }
                } else {
                    //删除按钮
                    List<ShoppingCar> alldb = null;

                    try {
                        alldb = db.findAll(ShoppingCar.class);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < mSelectState.size(); i++) {
                        int i1 = mSelectState.keyAt(i);
                        Boolean aBoolean = mSelectState.get(i1);
                        if (mSelectState.size() == all.size()) {
                            all.clear();
                            try {
                                db.delete(ShoppingCar.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            mSelectState.clear();
                            jsonDate();
                        } else {
                            if (aBoolean && all.size() != 0) {
                                String productID = all.get(i1).getProductID();
                                try {
                                    WhereBuilder whereBuilder = WhereBuilder.b();
                                    whereBuilder.and("ProductID", "=", productID);
                                    db.delete(ShoppingCar.class, whereBuilder);
                                    mSelectState.clear();
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                all.remove(i1);
                                refreshListView();
                            }
                        }

                    }

                }
                break;
        }
    }

    /**
     * 刷新数据或者加载数据
     */
    private void refreshListView() {
        List<ShoppingCar> date = all;
        adapter = new MyAdapter(all);
        MlistView.setAdapter(adapter);
        //点击的哪一个item数据
        MlistView.setOnItemClickListener(adapter);
    }

    /***
     * 适配器
     */
    class MyAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
        List<ShoppingCar> date;

        public MyAdapter(List<ShoppingCar> date) {
            this.date = date;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return date.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {

            ViewHolder holder = null;
            View view = convertView;
            if (view == null) {
                view = LayoutInflater.from(getContext()).inflate(R.layout.recyclerviewholder_shopping, null);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            ShoppingCar car = date.get(position);

            //设置数据
            bindListItem(holder, car);
            //数量的添加
            holder.add.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    int _id = (int) date.get(position).getId();
                    boolean selected = mSelectState.get(_id, false);
                    date.get(position).setNum(date.get(position).getNum() + 1);
                    //数据库中添加
                    try {
                        WhereBuilder whereBuilder = WhereBuilder.b();
                        whereBuilder.and("ProductID", "=", date.get(position).getProductID());
                        db.update(ShoppingCar.class, whereBuilder, new KeyValue("num", date.get(position).getNum()));
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    notifyDataSetChanged();
                    //价格增加
                    if (selected) {
                        Log.i(TAG, "onClick: " + selected);

                        totalPrice += date.get(position).getPrice();
                        carMoney.setText("￥" + totalPrice + "");

                    }

                }
            });
            //数量减少
            holder.reduce.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    // TODO Auto-generated method stub
                    if (date.get(position).getNum() == 1) {
                        return;
                    }
                    int _id = (int) date.get(position).getId();
                    Log.i(TAG, "onClick: " + mSelectState.toString() + _id + position);
                    boolean selected = mSelectState.get(position, false);
                    date.get(position).setNum(date.get(position).getNum() - 1);
                    WhereBuilder whereBuilder = WhereBuilder.b();
                    whereBuilder.and("ProductID", "=", date.get(position).getProductID());
                    notifyDataSetChanged();
                    try {
                        db.update(ShoppingCar.class, whereBuilder, new KeyValue("num", date.get(position).getNum()));
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    if (selected) {
                        Log.i(TAG, "onClick: " + selected);
                        totalPrice -= date.get(position).getPrice();
                        carMoney.setText("￥" + totalPrice + "");

                    }

                }
            });
            //在item中的图片的点击
            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(getContext(), FoodGoodsPageActivity.class);
                    String productID = date.get(position).getProductID();
                    String[] string = new String[2];
                    if (productID.contains("_D")) {

                        string[0] = productID;
                        string[1] = productID.replaceAll("_D", "");

                    } else {
                        string[0] = productID;
                        string[1] = productID + "_D";

                    }
                    intent.putExtra("productID", string);
                    startActivity(intent);
                }
            });
            //总数量的商品
            MyseSum = mSelectState.size();
            return view;
        }

        //在布局中加载数据
        private void bindListItem(ViewHolder holder, ShoppingCar data) {
            x.image().bind(holder.img, data.getImg());
            holder.name.setText(data.getName());
            holder.money.setText("￥" + (int) data.getPrice() + "");
            holder.number.setText(data.getType());
            holder.num.setText(data.getNum() + "");
            int _id = data.getId();
            boolean selected = mSelectState.get(_id, false);
            holder.checkBox.setChecked(selected);

        }


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            ShoppingCar car = all.get(position);
            Log.i(TAG, "onItemClick: " + position);
            ViewHolder holder = (ViewHolder) view.getTag();
            boolean selected = !mSelectState.get(position, false);

            //是否等于true
            Log.i(TAG, "onItemClick: " + selected);
            if (selected)

            {
                holder.checkBox.setChecked(true);
                mSelectState.put(position, true);
                //总价格添加
                totalPrice += car.getNum() * car.getPrice();
            } else

            {
                holder.checkBox.setChecked(false);
                mSelectState.remove(position);
                //总价格减少
                totalPrice -= car.getNum() * car.getPrice();

            }
            Log.i(TAG, "onItemClick: " + mSelectState.toString());
            //设置总价格
            carMoney.setText("￥" + totalPrice + "");
            //全选的checkbox是否选中
            if (mSelectState.size() == all.size())

            {
                checkAll.setChecked(true);
            } else

            {
                carMoney.setText("0.00");
                checkAll.setChecked(false);
            }

        }


    }

    class ViewHolder {

        TextView num, number, money, name, add, reduce;
        ImageView img;
        CheckBox checkBox;


        public ViewHolder(View view) {
            num = (TextView) view.findViewById(R.id.recycle_shopping_num);
            money = (TextView) view.findViewById(R.id.recycle_shopping_money);
            number = (TextView) view.findViewById(R.id.recycle_shopping_number);
            name = (TextView) view.findViewById(R.id.recycle_shopping_name);
            add = (TextView) view.findViewById(R.id.recycle_shopping_add);
            reduce = (TextView) view.findViewById(R.id.recycle_shopping_reduce);
            img = (ImageView) view.findViewById(R.id.recycle_shopping_img);
            checkBox = (CheckBox) view.findViewById(R.id.holder_shopping_checkBox);
        }
    }


}
